﻿#region summary

// Copyright (c)  YISH. All rights reserved.
// Licensed under the MIT License, See License.txt in the project root for license information.

#endregion

using System.Text.RegularExpressions;
using NSQL.Sharpen;

namespace NSQL.Expressions
{
    public class LikeExpression : BaseExpression, ILikeExpression
    {
        private static readonly Regex StartWithRegex = new Regex("^%[^%]*", RegexOptions.Compiled);
        private static readonly Regex EndWithRegex = new Regex("[^%]*%$", RegexOptions.RightToLeft | RegexOptions.Compiled);

        public IExpression Left { get; set; }
        public StringExpression Pattern { get; set; }

        public bool IsStartsWith => HasPattern && StartWithRegex.Match(Pattern.Value).Success;
        public bool IsEndsWith => HasPattern && EndWithRegex.Match(Pattern.Value).Success;
        public bool IsContains => !IsStartsWith && !IsEndsWith;

        public bool HasPattern => Pattern?.Value != null;

        public LikeExpression()
        {
        }

        public LikeExpression(IExpression left, StringExpression pattern)
        {
            Left = left;
            Pattern = pattern;
        }

        public override T Accept<T>(IExpressionVisitor<T> visitor) => visitor.Visit(this);
        public override void Accept(IExpressionVisitor visitor) => visitor.Visit(this);
        public override bool IsValid => Left.IsValid && Pattern.IsValid;
        protected override IExpression DeepCopy()
        {
            return new LikeExpression(Left.DeepClone(), Pattern.DeepClone())
            {
                Tag = Tag
            };
        }
    }
}